using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using viBook.Models;

namespace viBook.Controllers
{
    public class ChaptersController : Controller
    {
        private readonly IChapterRepository _chapterRepository;

        public ChaptersController()
            : this(new ChapterRepository())
        {
        }

        public ChaptersController(IChapterRepository chapterRepository)
        {
            this._chapterRepository = chapterRepository;
        }


        public ViewResult Index()
        {
            return View(_chapterRepository.All);
        }

        public ViewResult Details(int id)
        {
            return View(_chapterRepository.Find(id));
        }


        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Chapter chapter)
        {
            if (ModelState.IsValid)
            {
                _chapterRepository.InsertOrUpdate(chapter);
                _chapterRepository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }


        public ActionResult Edit(int id)
        {
            return View(_chapterRepository.Find(id));
        }


        [HttpPost]
        public ActionResult Edit(Chapter chapter)
        {
            if (ModelState.IsValid)
            {
                _chapterRepository.InsertOrUpdate(chapter);
                _chapterRepository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            return View(_chapterRepository.Find(id));
        }


        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            _chapterRepository.Delete(id);
            _chapterRepository.Save();

            return RedirectToAction("Index");
        }

    }
}

